<script setup lang="ts">
import { ref, markRaw, nextTick } from "vue";
import { useColumns } from "./columns";
import Plus from "~icons/ep/plus";
import Delete from "~icons/ep/delete";
import "plus-pro-components/es/components/dialog-form/style/css";
import "jsoneditor/dist/jsoneditor.min.css";
import { addKv, getKvInfo, updateKv } from "@/api/system";
import { handleTree } from "@/utils/tree";
import JsonEditor from "ceel-json-editor";
defineOptions({
  name: "SystemConfigure"
});
import {
  type PlusColumn,
  type FieldValues,
  PlusDialogForm
} from "plus-pro-components";
import {
  type Action,
  genFileId,
  UploadInstance,
  UploadProps,
  ElMessageBox,
  ElMessage
} from "element-plus";
import { isEmpty } from "@pureadmin/utils";

const edit = ref(false);

const rules = {
  key: [
    {
      required: true,
      message: "key必填"
    }
  ],

  remark: [
    {
      required: true,
      message: "备注必填"
    }
  ]
};

const formColumns: PlusColumn[] = [
  {
    label: "key",
    prop: "key",
    valueType: "input",
    tooltip: "请输入key"
  },
  {
    label: "value",
    prop: "value"
  },
  {
    label: "备注",
    prop: "remark",
    valueType: "input",
    tooltip: "请输入备注"
  },
  {
    label: "状态",
    prop: "status",
    valueType: "select",
    options: [
      {
        label: "草稿",
        value: 0
      },
      {
        label: "启用",
        value: 1
      }
    ]
  }
];
const visible = ref(false);
const values = ref<FieldValues>({ status: 0 });
const editorData = ref();
const { loading, columns, dataList, loadingConfig, adaptiveConfig, loadData } =
  useColumns();
const editClick = async row => {
  try {
    const res = await getKvInfo(row.id);
    const data = res.data;
    let myValue = data.value;
    if (typeof myValue === "object") {
      myValue = JSON.stringify(myValue);
    } else if (typeof myValue === "number") {
      myValue = myValue.toString();
    }
    const params = {
      key: data.key,
      value: myValue,
      remark: data.remark,
      status: data.status
    };
    editorData.value = myValue;

    values.value = params;
    edit.value = true;
    visible.value = true;
    console.log("tttt", params);
  } catch (error) {
    console.error(error);
  }
};
const infoClick = async row => {};
const add = () => {
  edit.value = false;
  values.value = { key: "", value: "", remark: "", status: 0 };
  visible.value = true;
};
const confirmLoading = ref(false);
const handleSubmit = async (value: FieldValues) => {
  const updatedValues = { ...values.value };

  confirmLoading.value = true;
  updatedValues.value = isEmpty(editorData.value)
    ? values.value.value
    : editorData.value;
  if (edit.value) {
    try {
      await updateKv(updatedValues);
      visible.value = false;
      confirmLoading.value = false;
      formRef.value?.formInstance?.resetFields();
      loadData();
      ElMessage.success("修改成功");
    } catch (error) {
      confirmLoading.value = false;
      console.log(error, "error");
    }
  } else {
    try {
      await addKv(updatedValues);
      visible.value = false;
      confirmLoading.value = false;
      formRef.value?.formInstance?.resetFields();
      loadData();
    } catch (error) {
      confirmLoading.value = false;
      console.log(error, "error");
    }
  }
};
const formRef = ref();
const jsonEditorOptions = {
  mode: "text", // Override default configuration
  modes: ["code", "text"],
  language: "zh-CN", // Override default configuration
  onChange: (v: string) => {
    // Add change event
    console.log("valueJSON", v);
  },

  onChangeText: (v: string) => {
    // Add change event
    editorData.value = v;
  }
};
</script>

<template>
  <ElCard>
    <template #header>
      <ElPageHeader :icon="null">
        <template #title>
          <h3>系统配置</h3>
        </template>
        <template #extra>
          <div class="flex flex-row items-end justify-end">
            <el-button type="primary" @click="add">
              <el-icon :size="15" color="#fff">
                <IconifyIconOffline :icon="Plus" />
              </el-icon>
              添加配置
            </el-button>
          </div>
        </template>
      </ElPageHeader>
    </template>
    <pure-table
      ref="tableRef"
      showOverflowTooltip
      border
      adaptive
      :adaptiveConfig="adaptiveConfig"
      row-key="id"
      alignWhole="center"
      :loading="loading"
      :loading-config="loadingConfig"
      :data="dataList"
      :columns="columns"
    >
      <template #operation="{ row }">
        <el-button type="info" size="small" @click="infoClick(row)"
          >查看</el-button
        >
        <el-button type="primary" size="small" @click="editClick(row)"
          >编辑</el-button
        >
      </template>
    </pure-table>
    <PlusDialogForm
      ref="formRef"
      v-model:visible="visible"
      v-model="values"
      :form="{ columns: formColumns, rules, labelWidth: 120 }"
      :dialog="{ confirmLoading }"
      :title="edit ? '编辑配置' : '添加配置'"
      @confirm="handleSubmit"
    >
      <template #plus-field-key>
        <el-input v-model="values.key" :disabled="edit" />
      </template>
      <template #plus-field-value>
        <JsonEditor
          id="test"
          v-model="values.value"
          width="100%"
          :option="jsonEditorOptions"
        />
      </template>
    </PlusDialogForm>
  </ElCard>
</template>

<style scoped>
::deep .wot-message-box__icon--warning {
  --el-messagebox-color: red;
  color: red !important;
  fill: red !important;
}
</style>
